//
//  BillDatePicker.swift
//  Speek
//
//  Created by MikeHo on 2023/6/28.
//

import SwiftUI
import CoreData

struct BillDatePicker: View {
    @Binding var monthlyBillShowing : [MonthlyBill]
    @Binding var yearArray : [String]
    @Binding var monthArray : [String]
    @Binding var selectYear: String
    @Binding var selectMonth: String
    //@Binding var scrollToBillID: UUID? // 添加一个变量来保存要滚动到的账单ID
    
    @Environment(\.dismiss) private var dismiss
    @Environment(\.managedObjectContext) private var context

    var body: some View {
        NavigationStack{
            
            HStack{
                Picker("",selection: $selectYear){
                    ForEach(yearArray,id:\.self){year in
                        Text(year)
                    }
                }
                .pickerStyle(WheelPickerStyle())
                
                
                Picker("",selection: $selectMonth){
                    ForEach(monthArray,id:\.self){month in
                        Text(month)
                    }
                }
                .pickerStyle(WheelPickerStyle())
                
            }
            //检查年份与月份是否相关
            .onChange(of: selectYear) { newYear in
                if !monthArray.contains(selectMonth) || !hasData(for: selectYear, and: selectMonth) {
                    selectMonth = ""
                }
            }
            .onChange(of: selectMonth) { newMonth in
                if !hasData(for: selectYear, and: selectMonth) {
                    selectYear = ""
                }
            }
            
            //完成按钮
            .toolbar{
                ToolbarItem(placement: .navigationBarTrailing){
                    Button {
                        // 更新滚动到的账单ID
                        //scrollToBillID = getFirstBillID(for: selectYear, month: selectMonth)
                        //关闭日期选择界面
                        dismiss()
                    } label: {
                        Text("完成")
                    }
                }
            }
        }
        .navigationTitle("选择日期")
        .preferredColorScheme(.dark)
        .navigationBarTitleDisplayMode(.inline)
        
    }
    
    /*
    // 获取选择日期的第一个账单的ID
    private func getFirstBillID(for year: String, month: String) -> UUID? {
        guard let monthlyBill = monthlyBillShowing.first(where: { $0.year == year && $0.month == month }),
              let firstBill = monthlyBill.billsArray.first else {
            return nil
        }
        return firstBill.id
    }
     */
    
    
    //判断日期是否有账单
    private func hasData(for year: String, and month: String) -> Bool {
        return monthlyBillShowing.contains { bill in
            bill.year == year && bill.month == month
        }
    }
}
